<!-- 文章管理 新增/修改 -->
<template>
  <div>
    <el-dialog :title="roleData.title" :visible.sync="roleData.showModal" width="850px" top="5vh">
      <el-form label-width="170px" :model="data" ref="update" :rules="rules" v-loading="showLoading" :element-loading-text="$t('lan.dataLoading')">
        <el-row>
          <el-col :offset="3" :span="18">
            <el-form-item :label="$t('lan.mainTitle')" prop="title">
              <el-input size="medium" :placeholder="$t('lan.pleaseTitle')" v-model="data.title"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :offset="3" :span="18">
            <el-form-item :label="$t('lan.subTitle')" prop="subTitle">
              <el-input size="medium" :placeholder="$t('lan.pleaseSub')" v-model="data.subTitle"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :offset="3" :span="18">
            <el-form-item :label="$t('lan.category')" prop="type">
              <el-select v-model="data.type" size="medium" :placeholder="$t('lan.pleaseCategory')">
                <el-option v-for="item in typeList" :key="item.id" :label="item.name" :value="item.id"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :offset="3" :span="18">
            <el-form-item :label="$t('lan.purchaseNot')">
              <el-radio-group v-model="data.buyFlag">
                <el-radio label="1">{{$t('lan.yes')}}</el-radio>
                <el-radio label="2">{{$t('lan.no')}}</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :offset="3" :span="18">
            <el-form-item :label="$t('lan.customNot')">
              <el-radio-group v-model="data.customizeFlag">
                <el-radio label="1">{{$t('lan.yes')}}</el-radio>
                <el-radio label="2">{{$t('lan.no')}}</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :offset="3" :span="18">
            <el-form-item :label="$t('lan.uploadVideo')">
              <el-upload name="uploadFile" :headers="tokenimg" :on-success="onSuccess" :on-progress="uploadVideoProcess" :before-upload="beforeUpload" :action="request.server + '/attachment/fileUpload'" :show-file-list="false" :auto-upload="true">
                <div class="upload-box" v-if="data.picUrl =='' && videoFlag == false">
                  <i slot="default" class="el-icon-plus" style="font-size:30px;color: #8c939d;"></i>
                </div>
                <video style="height:148px;width:200px" v-if="data.picUrl !='' && common.matchFileSuffixType(data.picUrl,'video')" :src="data.picUrl" controls="controls">您的浏览器不支持视频播放</video>
                <img v-if="data.picUrl!='' && common.matchFileSuffixType(data.picUrl,'image')" :src="data.picUrl" style="height:148px;width:148px" />
                <el-progress type="circle" v-if="videoFlag == true" :percentage="videoUploadPercent" style="margin-top:30px;"></el-progress>
                <!-- <div slot="file" slot-scope="{file}">
                  <img class="el-upload-list__item-thumbnail" :src="file.url" alt="">
                  <video :src="file.url"></video>
                  <span class="el-upload-list__item-actions">
                    <span class="el-upload-list__item-preview" @click="handlePictureCardPreview(file)">
                      <i class="el-icon-zoom-in"></i>
                    </span>
                    <span v-if="!disabled" class="el-upload-list__item-delete" @click="handleDownload(file)">
                      <i class="el-icon-download"></i>
                    </span>
                    <span v-if="!disabled" class="el-upload-list__item-delete" @click="handleRemove(file)">
                      <i class="el-icon-delete"></i>
                    </span>
                  </span>
                </div> -->
              </el-upload>
              <!-- <el-dialog :visible.sync="dialogVisible">
                <img v-if="!isVideo" width="100%" :src="dialogImageUrl" alt="">
                <video v-else width="100%" :src="videoUrl" controls="controls"></video>
              </el-dialog> -->
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :offset="3" :span="18">
            <el-form-item :label="$t('lan.detail')" prop="content">
              <quill-editor v-model="data.content" :options="custom"></quill-editor>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <!-- 底部按钮开始 -->
      <span slot="footer" class="dialog-footer">
        <el-button size="medium" type="primary" @click="add">{{$t('lan.submit')}}</el-button>
        <el-button size="medium" @click="roleData.showModal = false">{{$t('lan.cancel')}}</el-button>
      </span>
      <!-- 底部按钮结束 -->
    </el-dialog>
  </div>
</template>
<script>
export default {
  props: ["roleData"],
  data () {
    return {
      isVideo: false,
      dialogImageUrl: '',
      videoUrl: '',
      dialogVisible: false,
      disabled: false,
      tokenimg: {
        token: sessionStorage.getItem("token")
      }, // 图片请求头
      typeList: [],
      showLoading: false, //是否显示loading
      title: "", //标题
      //需要提交的数据
      data: {
        title: "",
        subTitle: '',
        type: "",
        picUrl: "",
        buyFlag: '1',
        content: '',
        customizeFlag: '1',
      },
      custom: {
        modules: {
          toolbar: [
            ["bold", "italic", "underline", "strike"], //加粗，斜体，下划线，删除线
            ["blockquote", "code-block"], //引用，代码块
            [{ header: 1 }, { header: 2 }], // 标题，键值对的形式；1、2表示字体大小
            [{ list: "ordered" }, { list: "bullet" }], //列表
            [{ script: "sub" }, { script: "super" }], // 上下标
            [{ indent: "-1" }, { indent: "+1" }], // 缩进
            [{ direction: "rtl" }], // 文本方向
            // [{ 'size': ['small', false, 'large', 'huge'] }], // 字体大小
            // [{ 'header': [1, 2, 3, 4, 5, 6, false] }],     //几级标题
            // [{ 'color': [] }, { 'background': [] }],     // 字体颜色，字体背景颜色
            // [{ 'font': [] }],     //字体
            [{ align: [] }], //对齐方式
            // ['clean'],    //清除字体样式
            ["image"] //上传图片、上传视频
          ]
        },
        theme: "snow", // 默认主题
        placeholder: this.$t('lan.pleaseContent')
      },

      videoUploadPercent: 0,
      videoFlag: false,
      //表单校验
      rules: {
        title: [{ required: true, message: this.$t('lan.mainEmpty'), trigger: "blur" }],
        subTitle: [{ required: true, message: this.$t('lan.subheadingEmpty'), trigger: "blur" }],
        type: [{ required: true, message: this.$t('lan.pleaseCategory'), trigger: "blur" }]
      }
    };
  },
  methods: {
    uploadVideoProcess (event, file, fileList) {
      this.videoFlag = true;
      this.videoUploadPercent = file.percentage;
    },
    // 图片上传成功后，后台返回图片的路径
    onSuccess (res) {
      this.videoUploadPercent = 0
      this.videoFlag = false;
      if (res.code == 200) {
        this.data.picUrl = res.data;
      }
    },
    // 图片校验
    beforeUpload (file) {
      var testmsg = /^image\/(jpeg|png|jpg)$/.test(file.type);
      if (file.type === 'image/jpeg') {
        if (!testmsg) {
          return this.$message.error(this.$t('lan.uploadFormat'));
        }
      } else {
        if (['video/mp4', 'video/ogg', 'video/flv', 'video/avi', 'video/wmv', 'video/rmvb'].indexOf(file.type) == -1) {
          return this.$message.error(this.$t('lan.pleaseVideo'));
        }
      }
    },
    //新增、修改文章
    add () {
      this.$refs["update"].validate(async valid => {
        if (valid) {
          if (this.data.type == "4") {
            if (this.data.picUrl == '') {
              this.$message({ message: this.$t('lan.pleaseUpload'), type: 'error' })
              return;
            }
          }
          this.showLoading = true;
          let url =
            this.roleData.type == "create"
              ? "/product/save"
              : "/product/update";
          let httpMethod = this.roleData.type == "create" ? "POST" : "PUT";
          let result = await this.request.httpRequest(
            httpMethod,
            url,
            this.data
          );
          if (result.code == 200) {
            this.roleData.showModal = false;
            this.$message({ type: "success", message: result.msg });
            this.$emit("close");
          } else {
            this.$message({ type: "error", message: result.msg });
          }
          this.showLoading = false;
        }
      });
    },
    //获取详情
    async getDetail () {
      if (this.roleData.roleId) {
        this.showLoading = true
        let url = `/product/get/${this.roleData.roleId}`;
        let result = await this.request.httpRequest("GET", url);
        if (result.code == 200) {
          this.data.id = result.data.id;
          this.data.title = result.data.title;
          this.data.subTitle = result.data.subTitle;
          this.data.type = Number(result.data.type);
          this.data.picUrl = result.data.picUrl;
          this.data.buyFlag = result.data.buyFlag;
          this.data.content = result.data.content;
          this.data.customizeFlag = result.data.customizeFlag;
          this.showLoading = false
        } else {
          this.$message({ type: "error", message: result.msg });
          this.showLoading = false
        }
      }
    },
    // 获取类型
    async getterm () {
      const url = '/category/queryList'
      const result = await this.request.httpRequest('POST', url, { pid: 0 });
      if (result.code === 200) {
        this.typeList = result.data
      }
    }
  },
  created () {
    this.getterm();
    this.getDetail();
  }
};
</script>
<style>
.ql-container.ql-snow {
  min-height: 200px;
}
</style>
<style scoped>
.upload-box {
  background-color: #fbfdff;
  border: 1px dashed #c0ccda;
  border-radius: 6px;
  box-sizing: border-box;
  width: 148px;
  height: 148px;
  cursor: pointer;
  line-height: 146px;
  vertical-align: top;
}
</style>
